import io from 'socket.io-client';
import store from '../store/store'
import { setParticipants, setRoomId } from '../store/action';
import { handleSignalingData, prepareNewPeerConnection, removePeerConnection } from './webRTCHandler';
const SERVER = 'http://192.168.100.19:8000';

let socket = null;
export const connectWithSocketIOServer = () => {
    socket = io(SERVER);
    socket.on('connect',() => {
        //alert(socket.id);
    });
    socket.on('room-id',(data) =>{
        const {roomId} = data;
        store.dispatch(setRoomId(roomId))
    })
    socket.on('room-update',(data)=>{
        const {connectedUsers} = data;
        store.dispatch(setParticipants(connectedUsers))
    })

    //
    socket.on('conn-prepare',(data) =>{
        console.log('receive conn-prepare');
        //alert('receive conn-prepare');
        const {connUserSocketId} = data;
        //alert(connUserSocketId)
        prepareNewPeerConnection(connUserSocketId,false);

        //通知发起方 我已准备好可以进行webrtc链接
        socket.emit('conn-init',{connUserSocketId:connUserSocketId});
    })
    socket.on('conn-signal',(data)=>{
        handleSignalingData(data);
    })
    socket.on('conn-init',(data) =>{
        const {connUserSocketId} = data;
        prepareNewPeerConnection(connUserSocketId,true);
    })
    socket.on('user-disconnected',(data) =>{
       removePeerConnection(data);
    })
};
//主持人创建房间
export const createNewRoom = (identity) =>{
    let data = {identity:identity,}
    socket.emit('create-new-room',data)
}

//加入房间
export const joinRoom = (identity,roomId) => {
    const data = {
        roomId:roomId,
        identity:identity,
    }
    socket.emit('join-room',data);
}
//将信令服务器发送到服务器
export const signalPeerData = (data) =>{
    socket.emit('conn-signal',data);
}